package com.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;




import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.service.findService;

import serviceIface.ServiceIface;

import domain.Things;

public class insertInfo extends HttpServlet {
	private ServiceIface serviceiface;
	/**
	 * Constructor of the object.
	 */
	public insertInfo() {
		serviceiface=new findService();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
        doGet(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8"); 
		String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
		String abc="";
		 Map<String, String> map=new HashMap<String, String>();
		 String filename="";
		
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            //file.mkdir();
			//System.out.println("up "+ savePath);
        }
        
       DiskFileItemFactory factory=new DiskFileItemFactory();
       ServletFileUpload upload=new ServletFileUpload(factory);
       upload.setHeaderEncoding("UTF-8");
       if(!ServletFileUpload.isMultipartContent(request)){

    	 return;
       }
       try {
		List<FileItem> list = upload.parseRequest(request);
		for(FileItem item : list){

        if(item.isFormField()){
        String name = item.getFieldName();

          String value = item.getString("UTF-8");
           map.put(name, value);
          }else{       

              filename = item.getName();
               if(filename==null || filename.trim().equals("")){
            
                  continue;
                    }
               String fileType=filename.substring(filename.lastIndexOf('.')+1,filename.length());
               if(fileType.equals("jpg")||fileType.equals("png" )||fileType.equals("bmp")){
            	   
               
               String phone=map.get("phone");
               filename = filename.substring(filename.lastIndexOf("\\")+1);
               savePath = phonelib(savePath,phone)+"/"+filename;
				InputStream in = item.getInputStream();

                FileOutputStream out = new FileOutputStream(savePath);
                byte buffer[] = new byte[1024];
                int count=0;
                while ((count = in.read(buffer)) >0) {
                    out.write(buffer, 0, count);
                }

                  in.close();
                 out.close();      
          }else{  
        	  RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");  
        	    try {  
        	      rd.forward(request, response);  
        	           return;  
        	        }catch(Exception e){
        		  
        	       }
              }
          }
		}
		
		
	} catch (FileUploadException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

              
		
		Date date=new Date();
		String time=1900+date.getYear()+"-"+date.getMonth()+1+"-"+date.getDate();
		String status="1";
		String src="";
		if(filename==null){
			src="";
		}else{
			src=filename;
		}
		String name=map.get("name");
		String type=map.get("type");
		String place=map.get("place");
		String describle=map.get("describle");
		String phone=map.get("phone");
		String qq=map.get("qq");
		String key=map.get("key");
		if(name.equals("")||name==null||type.equals("")||type==null||place.equals("")||place==null||describle.equals("")||describle==null||phone.equals("")||phone==null||key.equals("")||key==null){
			request.getRequestDispatcher("/insertInformation.jsp").forward(request, response);
		}else{
		
			Things thing=new Things("",type,time,describle,status,place,src,name,phone,qq,key);
			boolean b=serviceiface.addInfor(thing);
			if(b){
			request.getRequestDispatcher("/success.jsp").forward(request, response);
			}
		}
	
	}
	
	
	private String makeFileName(String filename){  //2.jpg

		    return UUID.randomUUID().toString() + "_" + filename;
			    }
	
	
	public void init() throws ServletException {
		// Put your code here
	}
	
	private String phonelib(String savePath,String phone){
	
		
		String dir=savePath+"/"+phone;
		//System.out.println(dir);
		File file=new File(dir);
		if(!file.exists()){
			
			file.mkdirs();

		}
		return dir;
	}

}
